package com.spider.im.chat.service;

import com.spider.im.chat.proto.ChatProto;
import io.netty.channel.ChannelHandlerContext;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class LoginService {
    //存储用户登录成功的客户端句柄
    private static final Map<String, ChannelHandlerContext> userLoginMap = new ConcurrentHashMap<>();

    public static void login(String userName, ChannelHandlerContext ctx) {

        userLoginMap.put(userName, ctx);
    }

    public static void logout(String userName) {
        ChannelHandlerContext ctx = userLoginMap.remove(userName);
        if (ctx != null) {
            // 1. 主动关闭连接
            ChatProto.MessageWrapper wrapper = ChatProto.MessageWrapper.newBuilder()
                    .setType(ChatProto.MessageType.LOGOUT)
                    .setPayload(ChatProto.Response.newBuilder()
                            .setSuccess(true)
                            .setMessage("用户退出登录")
                            .build().toByteString())
                    .build();
            ctx.writeAndFlush(wrapper);
            ctx.close();
        }
    }
}
